package com.wxb.controller;

import com.wxb.common.core.utils.DateUtils;
import com.wxb.common.core.utils.StringUtils;
import com.wxb.common.security.utils.SecurityUtils;
import com.wxb.common.util.*;
import com.wxb.common.core.web.domain.AjaxResult;
import com.wxb.common.util.CharUtil;
import com.wxb.domain.*;
import com.wxb.service.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * @Date 2025-05-30 14:15
 * @Version 1.0
 * @Description
 * @ClassName MallGoodsController
 **/
@RestController
@RequestMapping("/goods")
public class MallGoodsController {
    @Autowired
    private IMallGoodsService goodsService;
    @Autowired
    private IMallGoodsSpecificationService goodsSpecificationService;
    @Autowired
    private IMallProductService productService;
    @Autowired
    private IMallGoodsGalleryService goodsGalleryService;
    @Autowired
    private IMallGoodsIssueService goodsIssueService;
    @Autowired
    private IMallAttributeService attributeService;
    @Autowired
    private IMallBrandService brandService;
    @Autowired
    private IMallCommentService commentService;
    @Autowired
    private IMallUserService userService;
    @Autowired
    private IMallCommentPictureService commentPictureService;
    @Autowired
    private IMallCollectService collectService;
    @Autowired
    private IMallFootprintService footprintService;
    @Autowired
    private IMallCategoryService categoryService;
    @Autowired
    private IMallSearchHistoryService searchHistoryService;
    @Autowired
    private IMallRelatedGoodsService relatedGoodsService;
    @Autowired
    private IMallCouponService apiCouponService;
    @Autowired
    private IMallUserCouponService apiUserCouponService;
    @Autowired
    private IMallCartService cartService;

    @PostMapping(value = "index")
    public Object index() {
        //
        Map<String, Object> param = new HashMap<>();
        param.put("isDelete", 0);
        param.put("isOnSale", 1);
        List<MallGoodsEntity> goodsList = goodsService.queryList(param);
        //
        return AjaxResult.success(goodsList);
    }

    /**
     * 获取商品规格信息，用于购物车编辑时选择规格
     */
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "商品id", paramType = "path", required = true)})
    @PostMapping(value = "sku")
    public Object sku(Integer id) {
        Map<String, Object> resultObj = new HashMap<>();
        //
        Map<String, Object> param = new HashMap<>();
        param.put("goodsId", id);
        List<MallGoodsSpecificationEntity> goodsSpecificationEntityList = goodsSpecificationService.queryList(param);
        //
        List<MallProductEntity> productEntityList = productService.queryList(param);
        //
        resultObj.put("specificationList", goodsSpecificationEntityList);
        resultObj.put("productList", productEntityList);
        return AjaxResult.success(resultObj);
    }

    /**
     * 商品详情页数据
     */
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "商品id", paramType = "path", required = true),
            @ApiImplicitParam(name = "referrer", value = "商品referrer", paramType = "path", required = false)})
    @GetMapping(value = "detail")
    public Object detail(@RequestParam(value = "id") Integer id,@RequestParam(required = false) Long referrer) {
        Map<String, Object> resultObj = new HashMap<>();
        Long userId = SecurityUtils.getUserId();
        MallGoodsEntity info = goodsService.queryObject(id);
        Map<String, Object> param = new HashMap<>();
        param.put("goodsId", id);
        //
        Map<String, Object> specificationParam = new HashMap<>();
        specificationParam.put("fields", "gs.*, s.name");
        specificationParam.put("goodsId", id);
        specificationParam.put("specification", true);
        specificationParam.put("sidx", "s.sort_order");
        specificationParam.put("order", "asc");
        List<MallGoodsSpecificationEntity> goodsSpecificationEntityList = goodsSpecificationService.queryList(specificationParam);

        List<Map> specificationList = new ArrayList<>();
        //按规格名称分组
        for (int i = 0; i < goodsSpecificationEntityList.size(); i++) {
            MallGoodsSpecificationEntity specItem = goodsSpecificationEntityList.get(i);
            //
            List<MallGoodsSpecificationEntity> tempList = null;
            for (int j = 0; j < specificationList.size(); j++) {
                if (specificationList.get(j).get("specificationId").equals(specItem.getSpecificationId())) {
                    tempList = (List<MallGoodsSpecificationEntity>) specificationList.get(j).get("valueList");
                    break;
                }
            }
            //
            if (null == tempList) {
                Map<String, Object> temp = new HashMap<>();
                temp.put("specificationId", specItem.getSpecificationId());
                temp.put("name", specItem.getName());
                tempList = new ArrayList<>();
                tempList.add(specItem);
                temp.put("valueList", tempList);
                specificationList.add(temp);
            } else {
                for (int j = 0; j < specificationList.size(); j++) {
                    if (specificationList.get(j).get("specificationId").equals(specItem.getSpecificationId())) {
                        tempList = (List<MallGoodsSpecificationEntity>) specificationList.get(j).get("valueList");
                        tempList.add(specItem);
                        break;
                    }
                }
            }
        }
        //
        List<MallProductEntity> productEntityList = productService.queryList(param);
        //
        List<MallGoodsGalleryEntity> gallery = goodsGalleryService.queryList(param);
        Map<String, Object> ngaParam = new HashMap<>();
        ngaParam.put("fields", "nga.value, na.name");
        ngaParam.put("sidx", "nga.id");
        ngaParam.put("order", "asc");
        ngaParam.put("goodsId", id);
        List<MallAttributeEntity> attribute = attributeService.queryList(ngaParam);
        //
        Map<String, Object> issueParam = new HashMap<>();
//        issueParam.put("goodsId", id);
        List<MallGoodsIssueEntity> issue = goodsIssueService.queryList(issueParam);
        //
        MallBrandEntity brand = brandService.queryObject(info.getBrandId());
        //
        param.put("valueId", id);
        param.put("typeId", 0);
        Integer commentCount = commentService.queryTotal(param);
        List<MallCommentEntity> hotComment = commentService.queryList(param);
        Map<String, Object> commentInfo = new HashMap<>();
        if (null != hotComment && hotComment.size() > 0) {
            MallUserEntity commentUser = userService.queryObject(hotComment.get(0).getUserId());
            commentInfo.put("content", Base64Util.decode(hotComment.get(0).getContent()));
            commentInfo.put("addTime", DateUtils.timeToStr(hotComment.get(0).getAddTime(), DateUtils.YYYY_MM_DD));
            commentInfo.put("nickname", commentUser.getNickname());
            commentInfo.put("avatar", commentUser.getAvatar());
            Map<String, Object> paramPicture = new HashMap<>();
            paramPicture.put("commentId", hotComment.get(0).getId());
            List<MallCommentPictureEntity> commentPictureEntities = commentPictureService.queryList(paramPicture);
            commentInfo.put("picList", commentPictureEntities);
        }
        Map<String, Object> comment = new HashMap<>();
        comment.put("count", commentCount);
        comment.put("data", commentInfo);
        //当前用户是否收藏
        Map<String, Object> collectParam = new HashMap<>();
        collectParam.put("userId", SecurityUtils.getUserId());
        collectParam.put("valueId", id);
        collectParam.put("typeId", 0);
        Integer userHasCollect = collectService.queryTotal(collectParam);
        if (userHasCollect > 0) {
            userHasCollect = 1;
        }
        //记录用户的足迹
        MallFootprintEntity footprintEntity = new MallFootprintEntity();
        footprintEntity.setAddTime(System.currentTimeMillis() / 1000);
        footprintEntity.setGoodsBrief(info.getGoodsBrief());
        footprintEntity.setListPicUrl(info.getListPicUrl());
        footprintEntity.setGoodsId(info.getId());
        footprintEntity.setName(info.getName());
        footprintEntity.setRetailPrice(info.getRetailPrice());
        footprintEntity.setUserId(userId);
        if (null != referrer) {
            footprintEntity.setReferrer(referrer);
        } else {
            footprintEntity.setReferrer(0L);
        }
        footprintService.save(footprintEntity);
        //
        resultObj.put("info", info);
        resultObj.put("gallery", gallery);
        resultObj.put("attribute", attribute);
        resultObj.put("userHasCollect", userHasCollect);
        resultObj.put("issue", issue);
        resultObj.put("comment", comment);
        resultObj.put("brand", brand);
        resultObj.put("specificationList", specificationList);
        resultObj.put("productList", productEntityList);
        // 记录推荐人是否可以领取红包，用户登录时校验
        try {
            // 是否已经有可用的转发红包
            Map<String, Object> params = new HashMap<>();
            params.put("userId", userId);
            params.put("sendType", 2);
            params.put("unUsed", true);
            List<MallCouponEntity> enabledCouponVos = apiCouponService.queryUserCoupons(params);
            if ((null == enabledCouponVos || enabledCouponVos.size() == 0)
                    && null != referrer && null != userId) {
                // 获取优惠信息提示
                Map<String, Object> couponParam = new HashMap<>();
                couponParam.put("enabled", true);
                Integer[] sendTypes = new Integer[]{2};
                couponParam.put("sendTypes", sendTypes);
                List<MallCouponEntity> couponVos = apiCouponService.queryList(couponParam);
                if (null != couponVos && couponVos.size() > 0) {
                    MallCouponEntity couponVo = couponVos.get(0);
                    Map<String, Object> footprintParam = new HashMap<>();
                    footprintParam.put("goodsId", id);
                    footprintParam.put("referrer", referrer);
                    Integer footprintNum = footprintService.queryTotal(footprintParam);
                    if (null != footprintNum && null != couponVo.getMinTransmitNum()
                            && footprintNum > couponVo.getMinTransmitNum()) {
                        MallUserCouponEntity userCouponVo = new MallUserCouponEntity();
                        userCouponVo.setAddTime(new Date());
                        userCouponVo.setCouponId(couponVo.getId());
                        userCouponVo.setCouponNumber(CharUtil.getRandomString(12));
                        userCouponVo.setUserId(SecurityUtils.getUserId());
                        apiUserCouponService.save(userCouponVo);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return AjaxResult.success(resultObj);
    }

    /**
     * 　获取分类下的商品
     */
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "分类id", paramType = "path", required = true)})
    @GetMapping(value = "category")
    public Object category(@RequestParam("id") Integer id) {
        Map<String, Object> resultObj = new HashMap<>();
        //
        MallCategoryEntity currentCategory = categoryService.queryObject(id);
        //
        MallCategoryEntity parentCategory = categoryService.queryObject(currentCategory.getParentId());
        Map<String, Object> params = new HashMap<>();
        params.put("parentId", currentCategory.getParentId());
        List<MallCategoryEntity> brotherCategory = categoryService.queryList(params);
        //
        resultObj.put("currentCategory", currentCategory);
        resultObj.put("parentCategory", parentCategory);
        resultObj.put("brotherCategory", brotherCategory);
        return AjaxResult.success(resultObj);
    }

    /**
     * 　　获取商品列表
     */
    @ApiImplicitParams({@ApiImplicitParam(name = "categoryId", value = "分类id", paramType = "path", required = true),
            @ApiImplicitParam(name = "brandId", value = "品牌Id", paramType = "path", required = true),
            @ApiImplicitParam(name = "isNew", value = "新商品", paramType = "path", required = true),
            @ApiImplicitParam(name = "isHot", value = "热卖商品", paramType = "path", required = true)})
    @PostMapping(value = "list")
    public Object list(@RequestBody MallGoodsEntity mallGoodsEntity,
                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "size", defaultValue = "10") Integer size
                       ) {
        Long loginUserId = SecurityUtils.getUserId();
        Integer categoryId = mallGoodsEntity.getCategoryId();
        Integer brandId = mallGoodsEntity.getBrandId();
        String keyword = mallGoodsEntity.getKeywords();
        Integer isNew = mallGoodsEntity.getIsNew();
        Integer isHot = mallGoodsEntity.getIsHot();
        Map<String, Object> params = new HashMap<>();
        params.put("isDelete", 0);
        params.put("isOnSale", 1);
        params.put("brandId", brandId);
        params.put("keyword", keyword);
        params.put("isNew", isNew);
        params.put("isHot", isHot);
        params.put("page", page);
        params.put("limit", size);

        params.put("sidx", "id");
        params.put("order", "desc");

        //添加到搜索历史
        if (!StringUtils.isEmpty(keyword)) {
            MallSearchHistoryEntity searchHistoryVo = new MallSearchHistoryEntity();
            searchHistoryVo.setAddTime(System.currentTimeMillis() / 1000);
            searchHistoryVo.setKeyword(keyword);
            searchHistoryVo.setUserId(null != loginUserId ? loginUserId+"" : "");
            searchHistoryVo.setFrom("");
            searchHistoryService.save(searchHistoryVo);

        }
        //筛选的分类
        List<MallCategoryEntity> filterCategory = new ArrayList<>();
        MallCategoryEntity rootCategory = new MallCategoryEntity();
        rootCategory.setId(0);
        rootCategory.setName("全部");
        rootCategory.setChecked(false);
        filterCategory.add(rootCategory);
        //
        params.put("fields", "category_id");
        List<MallGoodsEntity> categoryEntityList = goodsService.queryList(params);
        params.remove("fields");
        if (null != categoryEntityList && categoryEntityList.size() > 0) {
            List<Integer> categoryIds = new ArrayList<>();
            for (MallGoodsEntity goodsVo : categoryEntityList) {
                categoryIds.add(goodsVo.getCategoryId());
            }
            //查找二级分类的parentId
            Map<String, Object> categoryParam = new HashMap<>();
            categoryParam.put("ids", categoryIds);
            categoryParam.put("fields", "parent_id");
            List<MallCategoryEntity> parentCategoryList = categoryService.queryList(categoryParam);
            //
            List<Integer> parentIds = new ArrayList<>();
            for (MallCategoryEntity categoryEntity : parentCategoryList) {
                parentIds.add(categoryEntity.getParentId());
            }
            //一级分类
            categoryParam = new HashMap<>();
            categoryParam.put("fields", "id,name");
            categoryParam.put("order", "asc");
            categoryParam.put("sidx", "sort_order");
            categoryParam.put("ids", parentIds);
            List<MallCategoryEntity> parentCategory = categoryService.queryList(categoryParam);
            if (null != parentCategory) {
                filterCategory.addAll(parentCategory);
            }
        }
        //加入分类条件
        if (null != categoryId && categoryId > 0) {
            List<Integer> categoryIds = new ArrayList<>();
            Map<String, Object> categoryParam = new HashMap<>();
            categoryParam.put("parentId", categoryId);
            categoryParam.put("fields", "id");
            List<MallCategoryEntity> childIds = categoryService.queryList(categoryParam);
            for (MallCategoryEntity categoryEntity : childIds) {
                categoryIds.add(categoryEntity.getId());
            }
            categoryIds.add(categoryId);
            params.put("categoryIds", categoryIds);
        }
        //查询列表数据
        params.put("fields", "id, name, list_pic_url, market_price, retail_price, goods_brief");
        List<MallGoodsEntity> goodsList = goodsService.queryList(params);
        //搜索到的商品
        for (MallCategoryEntity categoryEntity : filterCategory) {
            if (null != categoryId && (categoryEntity.getId() == 0 || categoryId.equals(categoryEntity.getId()))
                    ||null == categoryId&&null == categoryEntity.getId()) {
                categoryEntity.setChecked(true);
            } else {
                categoryEntity.setChecked(false);
            }
        }
        return AjaxResult.success(goodsList);
    }

    /**
     * 　　商品列表筛选的分类列表
     */
    @PostMapping(value = "filter")
    public Object filter(Integer categoryId,
                         String keyword, Integer isNew, Integer isHot) {
        Map<String, Object> params = new HashMap<>();
        params.put("isDelete", 0);
        params.put("isOnSale", 1);
        params.put("categoryId", categoryId);
        params.put("keyword", keyword);
        params.put("isNew", isNew);
        params.put("isHot", isHot);
        if (null != categoryId) {
            Map<String, Object> categoryParams = new HashMap<>();
            categoryParams.put("categoryId", categoryId);
            List<MallCategoryEntity> categoryEntityList = categoryService.queryList(categoryParams);
            List<Integer> categoryIds = new ArrayList<>();
            for (MallCategoryEntity categoryEntity : categoryEntityList) {
                categoryIds.add(categoryEntity.getId());
            }
            params.put("categoryId", categoryIds);
        }
        //筛选的分类
        List<MallCategoryEntity> filterCategory = new ArrayList<>();
        MallCategoryEntity rootCategory = new MallCategoryEntity();
        rootCategory.setId(0);
        rootCategory.setName("全部");
        // 二级分类id
        List<MallGoodsEntity> goodsEntityList = goodsService.queryList(params);
        if (null != goodsEntityList && goodsEntityList.size() > 0) {
            List<Integer> categoryIds = new ArrayList<>();
            for (MallGoodsEntity goodsEntity : goodsEntityList) {
                categoryIds.add(goodsEntity.getCategoryId());
            }
            //查找二级分类的parentId
            Map<String, Object> categoryParam = new HashMap<>();
            categoryParam.put("categoryIds", categoryIds);
            List<MallCategoryEntity> parentCategoryList = categoryService.queryList(categoryParam);
            //
            List<Integer> parentIds = new ArrayList<>();
            for (MallCategoryEntity categoryEntity : parentCategoryList) {
                parentIds.add(categoryEntity.getId());
            }
            //一级分类
            categoryParam.put("categoryIds", parentIds);
            List<MallCategoryEntity> parentCategory = categoryService.queryList(categoryParam);
            if (null != parentCategory) {
                filterCategory.addAll(parentCategory);
            }
        }
        return AjaxResult.success(filterCategory);
    }

    /**
     * 　　新品首发
     */
    @PostMapping(value = "new")
    public Object newAction() {
        Map<String, Object> resultObj = new HashMap<>();
        Map<String, Object> bannerInfo = new HashMap<>();
        bannerInfo.put("url", "");
        bannerInfo.put("name", "坚持初心，为你寻觅世间好物");
        bannerInfo.put("imgUrl", "https://platform-wxmall.oss-cn-beijing.aliyuncs.com/upload/20180727/1504208321fef4.png");
        resultObj.put("bannerInfo", bannerInfo);
        return AjaxResult.success(resultObj);
    }

    /**
     * 　　人气推荐
     */
    @PostMapping(value = "hot")
    public Object hot() {
        Map<String, Object> resultObj = new HashMap<>();
        Map<String, Object> bannerInfo = new HashMap<>();
        bannerInfo.put("url", "");
        bannerInfo.put("name", "大家都在买的严选好物");
        bannerInfo.put("imgUrl", "https://platform-wxmall.oss-cn-beijing.aliyuncs.com/upload/20180727/1504208321fef4.png");
        resultObj.put("bannerInfo", bannerInfo);
        return AjaxResult.success(resultObj);
    }

    /**
     * 　　商品详情页的大家都在看的商品
     */
    @GetMapping(value = "related")
    public Object related(@RequestParam("id") Integer id) {
        Map<String, Object> resultObj = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("goodsId", id);
        param.put("fields", "related_goods_id");
        List<MallRelatedGoodsEntity> relatedGoodsEntityList = relatedGoodsService.queryList(param);

        List<Integer> relatedGoodsIds = new ArrayList<>();
        for (MallRelatedGoodsEntity relatedGoodsEntity : relatedGoodsEntityList) {
            relatedGoodsIds.add(relatedGoodsEntity.getRelatedGoodsId());
        }

        List<MallGoodsEntity> relatedGoods = new ArrayList<MallGoodsEntity>();

        if (null == relatedGoodsIds || relatedGoods.size() < 1) {
            //查找同分类下的商品
            MallGoodsEntity goodsCategory = goodsService.queryObject(id);
            Map<String, Object> paramRelated = new HashMap<>();
            paramRelated.put("fields", "id, name, list_pic_url, retail_price");
            paramRelated.put("categoryId", goodsCategory.getCategoryId());
            relatedGoods = goodsService.queryList(paramRelated);
        } else {
            Map<String, Object> paramRelated = new HashMap<>();
            paramRelated.put("goodsIds", relatedGoodsIds);
            paramRelated.put("fields", "id, name, list_pic_url, retail_price");
            relatedGoods = goodsService.queryList(paramRelated);
        }
        resultObj.put("goodsList", relatedGoods);
        return AjaxResult.success(resultObj);
    }

    /**
     * 　　在售的商品总数
     */
    @PostMapping(value = "count")
    public Object count() {
        Map<String, Object> resultObj = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("isDelete", 0);
        param.put("isOnSale", 1);
        Integer goodsCount = goodsService.queryTotal(param);
        resultObj.put("goodsCount", goodsCount);
        return AjaxResult.success(resultObj);
    }

    /**
     * 　　获取商品列表
     */
    @PostMapping(value = "productlist")
    public Object productlist(Integer categoryId,
                              Integer isNew, Integer discount,
                              @RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "size", defaultValue = "10") Integer size,
                              String sort, String order) {
        Map<String, Object> params = new HashMap<>();
        params.put("isNew", isNew);
        params.put("page", page);
        params.put("limit", size);
        params.put("order", sort);
        params.put("sidx", order);
        //
        if ("price".equals(sort)) {
            params.put("sidx", "retail_price");
            params.put("order", order);
        } else if ("sell".equals(sort)) {
            params.put("sidx", "orderNum");
            params.put("order", order);
        } else {
            params.put("sidx", "id");
            params.put("order", "desc");
        }
        // 0不限 1特价 2团购
        if (null != discount && discount == 1) {
            params.put("isHot", 1);
        } else if (null != discount && discount == 2) {
            params.put("is_group", true);
        }
        //加入分类条件
        if (null != categoryId && categoryId > 0) {
            List<Integer> categoryIds = new ArrayList<>();
            Map<String, Object> categoryParam = new HashMap<>();
            categoryParam.put("parentId", categoryId);
            categoryParam.put("fields", "id");
            List<MallCategoryEntity> childIds = categoryService.queryList(categoryParam);
            for (MallCategoryEntity categoryEntity : childIds) {
                categoryIds.add(categoryEntity.getId());
            }
            categoryIds.add(categoryId);
            params.put("categoryIds", categoryIds);
        }
        //查询列表数据
        List<MallGoodsEntity> goodsList = goodsService.queryCatalogProductList(params);

        // 当前购物车中
        List<MallCartEntity> cartList = new ArrayList<>();
        if (null != SecurityUtils.getUserId()) {
            //查询列表数据
            Map<String, Object> cartParam = new HashMap<>();
            cartParam.put("userId", SecurityUtils.getUserId());
            cartList = cartService.queryList(cartParam);
        }
        if (null != cartList && cartList.size() > 0 && null != goodsList && goodsList.size() > 0) {
            for (MallGoodsEntity goodsVo : goodsList) {
                for (MallCartEntity cartVo : cartList) {
                    if (goodsVo.getId().equals(cartVo.getGoodsId())) {
                        goodsVo.setCartNum(cartVo.getNumber());
                    }
                }
            }
        }
        return AjaxResult.success(goodsList);
    }
}
